package cn.xiaolang.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 读取config.properties配置
 *
 * @author Dean
 * @date 2022-01-15
 */
public class ConfigUtils {

    private static final Properties properties = new Properties();
    private static final Logger log =  LoggerFactory.getLogger(ConfigUtils.class);

    static {
        try (InputStream in = ConfigUtils.class.getResourceAsStream("/config.properties")) {
            if (Objects.nonNull(in)) {
                properties.load(in);
            }
        } catch (IOException e) {
            log.error("load init file failed:", e);
        }
    }

    /**
     * 用inputStream读取properties配置文件
     *
     * @param confFileName the configured file
     */
    public static void setStreamProperties(String confFileName) {
        try (InputStream in = ConfigUtils.class.getResourceAsStream("/" + confFileName)) {
            if (Objects.nonNull(in)) {
                properties.load(in);
            }
        } catch (IOException e) {
            log.error("load certain config file failed:", e);
        }
    }

    /**
     * 用fileReader读取properties配置文件
     *
     * @param filePath 配置文件的路径
     */
    public static void setFileReaderProperties(String filePath) {
        try (FileReader fileReader = new FileReader(filePath)) {
            properties.load(fileReader);
        } catch (IOException e) {
            log.error("", e);
        }
    }

    /**
     * 从properties配置文件中根据key获取相应的value值
     *
     * @param key Key
     * @return the value corresponding with the key
     */
    public static String getFromProperties(String key) {
        String value = properties.getProperty(key);
        if (value != null) {
            value = value.trim();
        }
        return value;
    }

    /**
     * resourceBundle根据配置文件名加载配置文件
     *
     * @param baseName 配置文件名不带后缀
     * @return ResourceBundle
     */
    public static ResourceBundle getResourceBundle(String baseName) {
        return ResourceBundle.getBundle(baseName);
    }
}
